package service

import (
	"admin-nexus-backend/internal/dto"
	"admin-nexus-backend/internal/model"
	"admin-nexus-backend/pkg/logger"
	"time"

	"gorm.io/gorm"
)

type UserOperationLogService struct {
	db *gorm.DB
}

func NewUserOperationLogService(db *gorm.DB) *UserOperationLogService {
	return &UserOperationLogService{db: db}
}

// CreateLog 创建操作日志
func (s *UserOperationLogService) CreateLog(log *model.UserOperationLog) error {
	return s.db.Create(log).Error
}

// GetUserOperationLogList 获取用户操作日志列表
func (s *UserOperationLogService) GetUserOperationLogList(params *dto.UserOperationLogQueryParams) (*dto.PageResult, error) {
	var logs []model.UserOperationLog
	var total int64

	query := s.db.Model(&model.UserOperationLog{})

	// 条件筛选
	if params.UserID != nil && *params.UserID > 0 {
		query = query.Where("user_id = ?", *params.UserID)
	}
	if params.Title != "" {
		query = query.Where("title LIKE ?", "%"+params.Title+"%")
	}
	if params.URL != "" {
		query = query.Where("url LIKE ?", "%"+params.URL+"%")
	}
	if params.IP != "" {
		query = query.Where("ip LIKE ?", "%"+params.IP+"%")
	}

	// 计算总数
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 排序（按创建时间倒序）
	query = query.Order("created_at DESC")

	// 分页
	offset := (params.Page - 1) * params.PageSize
	if err := query.Offset(offset).Limit(params.PageSize).Find(&logs).Error; err != nil {
		return nil, err
	}

	// 确保 List 始终是数组，而不是 null
	if logs == nil {
		logs = []model.UserOperationLog{}
	}

	return &dto.PageResult{
		List:     logs,
		Total:    total,
		Page:     params.Page,
		PageSize: params.PageSize,
	}, nil
}

const userOperationLogRetentionDays = 30

// DeleteLogsOlderThan 删除超过指定天数的操作日志
func (s *UserOperationLogService) DeleteLogsOlderThan(days int) (int64, error) {
	if days <= 0 {
		return 0, nil
	}

	cutoff := time.Now().AddDate(0, 0, -days)
	result := s.db.Unscoped().Where("created_at < ?", cutoff).Delete(&model.UserOperationLog{})
	return result.RowsAffected, result.Error
}

// StartUserOperationLogCleanup 启动定期清理任务
func StartUserOperationLogCleanup(db *gorm.DB) {
	if db == nil {
		logger.Warn("跳过操作日志清理任务: 数据库实例为空")
		return
	}

	logService := NewUserOperationLogService(db)

	go func() {
		// 启动时立即执行一次清理
		if deleted, err := logService.DeleteLogsOlderThan(userOperationLogRetentionDays); err != nil {
			logger.Error("启动操作日志清理任务失败", logger.Err(err))
		} else if deleted > 0 {
			logger.Info("启动操作日志清理任务完成", logger.Int64("deletedRows", deleted))
		}

		ticker := time.NewTicker(24 * time.Hour)
		defer ticker.Stop()

		for range ticker.C {
			if deleted, err := logService.DeleteLogsOlderThan(userOperationLogRetentionDays); err != nil {
				logger.Error("执行操作日志清理任务失败", logger.Err(err))
			} else if deleted > 0 {
				logger.Info("执行操作日志清理任务完成", logger.Int64("deletedRows", deleted))
			}
		}
	}()
}
